package com.xiang.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiang.doman.Good;
import com.xiang.doman.Order;
import com.xiang.doman.OrderStatus;
import com.xiang.feign.AccountFeign;
import com.xiang.feign.GoodFeign;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xiang.action.impl.OrderActionImpl;
import com.xiang.mapper.OrderMapper;
@Slf4j
@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Autowired
    private GoodFeign goodFeign;
    @Autowired
    private AccountFeign accountFeign;
    @Autowired
    OrderActionImpl orderActionService;

    @GlobalTransactional
    public String placeOrder(int countId, int goodId, int num) {
        Good good = goodFeign.findById(goodId);

        double amount = good.getGoodPrice() * num;
        Order order = Order.builder().status(OrderStatus.CREATE).id(System.nanoTime())
                .goodId(goodId).accountId(countId).goodNum(num).orderAmount(amount).build();
        log.info("Order== {}",order);
        // TCC 需要代理执行三个方法
        orderActionService.tryOrder(null,order);
        // 减库存
        goodFeign.reduceStock(goodId, num);
        //扣款
        accountFeign.reduceMoney(countId, amount);
        return "success";
    }

}
